<?php
defined('BASEPATH') or exit('No direct script access allowed');
/**
 * 股票数据模型
 */
class Curlmodel extends CI_model {

	/**
	 * [getCookie 获取指定地址的cookie]
	 *
	 * @param [type]  $url [description]
	 * @return [type]      [description]
	 */
	public function getCookie($url = '') {
		// 指定cookie文件存放地址
		$cookie_file = tempnam(sys_get_temp_dir(), "cookies");
		$ch = curl_init($url); //初始化
		curl_setopt($ch, CURLOPT_HEADER, 0); //不返回header部分
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串，而非直接输出
		curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); //存储cookies到指定的临时文件中
		curl_exec($ch);
		curl_close($ch);
		return $cookie_file;
	}

	/**
	 * [getCookie 获取指定地址的cookie]
	 *
	 * @param [type]  $url [description]
	 * @return [type]      [description]
	 */
	public function getCookieByHttps($url = '') {
		// 指定cookie文件存放地址
		// var_dump(sys_get_temp_dir());
		$cookie_file = tempnam(sys_get_temp_dir(), "cookies");
		$ch = curl_init($url); //初始化
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
		curl_setopt($ch, CURLOPT_HEADER, 0); //不返回header部分
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串，而非直接输出
		curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); //存储cookies到指定的临时文件中
		curl_exec($ch);
		curl_close($ch);
		return $cookie_file;
	}

	/**
	 * 获取指定地址的网页内容
	 *
	 * @param string  $url [description]
	 * @return [type]      [description]
	 */
	public function curl($url = '', $cookie_file = '') {
		// 初始化curl类
		$ch = curl_init();
		// 设置网页地址
		curl_setopt($ch, CURLOPT_URL, $url);
		// 设定curl不返回头信息
		curl_setopt($ch, CURLOPT_HEADER, 0);
		// 设定curl不在网页中直接显示抓取内容
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// 携带cookie访问指定页面
		curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
		// 执行抓取
		$content = curl_exec($ch);
		// 关闭curl资源
		curl_close($ch);
		return $content;
	}

	/**
	 * 使用https协议抓取网页内容
	 * @param  [type]  $url     [description]
	 * @param  array   $data    [description]
	 * @param  array   $header  [description]
	 * @param  integer $timeout [description]
	 * @return [type]           [description]
	 */
	public function curl_https($url, $cookie_file = '') {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
		curl_setopt($ch, CURLOPT_URL, $url);
		// 设定curl不返回头信息
		curl_setopt($ch, CURLOPT_HEADER, 0);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// 携带cookie访问指定页面
		curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);

		$response = curl_exec($ch);

		if ($error = curl_error($ch)) {
			die($error);
		}
		curl_close($ch);
		return $response;
	}

	/**
	 * 获取雪球行情中心沪深一览页面中所有股票的数量
	 */
	public function GetTotalPages() {
		// 取得cookie文件
		$cookie_file = $this->getCookieByHttps('https://xueqiu.com/hq#exchange=CN&firstName=1&secondName=1_0');
		// var_dump($cookie_file);
		// 抓取数据
		$string = $this->curl_https('https://xueqiu.com/stock/cata/stocklist.json?page=1&size=30&order=desc&orderby=percent&type=11%2C12&_=1475149781606', $cookie_file);
		// var_dump($string);
		$array = json_decode($string, true);
		return $array['count']['count'];
	}

	/**
	 * 过滤pre st b 指数
	 */
	public function filterCode(array $data) {
		$stack = array();
		for ($i = 0; $i < sizeof($data); $i++) {
			if (!(preg_match($this->pattern1, $data[$i]['scode']) || preg_match($this->pattern2, $data[$i]['sname']))) {
				array_push($stack, $data[$i]);
			}
		}
		return $stack;
	}

	/**
	 * 转换数组格式，使之适合搜索项目名称
	 */
	public function transform2string($array) {
		foreach ($array as $key => $value) {

			if (!is_string($value)) {
				$title[$key] = $value[0];
			}
		}
		return $title;
	}

	/**
	 * 获取指定项目的键名
	 */
	public function getFinanceArrayKey($value = '', $title) {
		return array_search($value, $title);
	}

	/**
	 * 转换json格式为数组变量
	 */
	public function json2array($json) {
		$array = json_decode($json, $assoc = true);
		return $array;
	}

	/**
	 * 将雪球的字段名转换为数据表中的字段
	 */
	public function xueqiu2stock(array $array) {
		foreach ($array['stocks'] as $key => $value) {
			$data[$key]['symbol'] = $value['symbol'];
			$data[$key]['scode'] = $value['code'];
			$data[$key]['sname'] = $value['name'];
		}
		return $data;
	}

	/**
	 * 将空字符串转为为null，否则返回原字符串
	 * 以方便SQL插入、更新
	 */
	public function white2null($string) {
		if (empty($string)) {
			return null;
		} else {
			return $string;
		}
	}

	/**
	 * 取得指定日期的现金流数据
	 */
	public function getCashData($reportDate, $cashData) {
		// 取得数据对应的键名
		$jykey = array_search('经营现金流量净额', $cashData['title']);
		$tzkey = array_search('投资现金流量净额', $cashData['title']);
		$czkey = array_search('筹资现金流量净额', $cashData['title']);

		$key = array_search($reportDate, $cashData['report'][0]);
		// 此函数可能返回布尔值 FALSE，但也可能返回等同于 FALSE 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。
		if ($key !== false) {
			$info['jyxjllje'] = $this->white2null($cashData['report'][$jykey][$key]);
			$info['tzxjllje'] = $this->white2null($cashData['report'][$tzkey][$key]);
			$info['czxjllje'] = $this->white2null($cashData['report'][$czkey][$key]);
			return $info;
		} else {
			$info['jyxjllje'] = null;
			$info['tzxjllje'] = null;
			$info['czxjllje'] = null;
			return $info;
		}
	}

	/**
	 * 获得指定代码的股票实时价格
	 */
	public function getPriceBySymbol($symbol = 'SZ300059') {
		$this->output->enable_profiler(true);
		// 第一步：从雪球抓取指定代码的公司数据
		$cookies = $this->cookie_file;
		$url = 'http://xueqiu.com/v4/stock/quote.json?code=SZ300059';
		$main = $this->Curlmodel->curl($url, $cookies);
		var_dump($main, $cookies);
	}

	// 从给定的数组中查找市值数据
	public function getMC($symbol, $array) {
		foreach ($array as $key => $value) {
			if ($array[$key]['symbol'] == $symbol) {
				return round(number_format((float) $array[$key]['marketCapital'], 0, '', '') / 100000000);
			}
		}
	}

	// 将进度信息存储到数据库
	public function saveProgressingInfo($pname = '', $pvalue = '') {
		$data = array(
			'pname' => $pname,
			'pvalue' => $pvalue,
		);
		$this->db->where(array('pname' => $pname))->replace('progress', $data);
	}

	// 读取指定任务的进度信息
	public function getProgressing($pname = '') {
		$data = $this->db->get_where('progress', array('pname' => $pname))->result_array();
		return $data[0]['pvalue'];
	}
}
